﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace HauhaltsPlaner
{

    public partial class Form1 : Form
    {
        DataTable table;
        DataTable EinnahmenDt;
        DataTable AusgabenDt;

        //Property
        public DataTable Kategorietable { get; set;}
    

        public Form1()
        {
            InitializeComponent();
          //  Form2 form2 = new Form2();
          //  form2.Show();
        }
                    public event TabControlEventHandler TabSelectedEvent;


        private void Form1_Load(object sender, EventArgs e)
        {
          

            //Eventhandler for onTabChanging
            tabControl1.SelectedIndexChanged += new System.EventHandler(this.tabControl1_SelectedIndexChanged);
           // dateTimePicker2.Value = dateTimePicker3.Value.AddDays(-7);
            InitForm();
            InitToolTips();

            //setup DataTable
            table = new DataTable();
            

            table.Columns.Add("Datum", typeof(DateTime));
            table.Columns.Add("Typ", typeof(string));
            table.Columns.Add("Betrag", typeof(double));
            table.Columns.Add("Kategorie", typeof(String));
            table.Columns.Add("Beschreibung", typeof(String));
            table.Columns.Add("Stand", typeof(double));

            // table.Rows.Add(new DateTime(2012,01,01), "Ausgaben", -500, "Essen", "teuer", -500);
            // table.ReadXml("D:/Mydata.xml");
            InitProfiles();

            
            dataGridView1.DataSource = table;
            
            for (int j = 1; j < 6; j++)
            {
                dataGridView1.Columns[j].ReadOnly = true;
            }
    
            dataGridView1.Columns[0].ReadOnly = false;
            
            dataGridView1.AllowUserToResizeColumns = false;
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
           
            setupMoney();
            
  
        }

        private void Speichern_Click(object sender, EventArgs e)
        {
            IOHandler writer = new IOHandler();
            writer.saveDataTable((string)comboBox3.SelectedItem, "GridData",table);
            toolStripStatusLabel1.Text = "Speichern abgeschlossen...";
            InitForm();
            setupMoney();
        }

        //Übertragen Cmd
        private void button1_Click(object sender, EventArgs e)
        {
            // minor bug fixed: check whether text boxes are empty and leave the method if so
            if (textBox1.Text.Trim() == "" || textBox2.Text.Trim() == "" || comboBox1.SelectedItem ==null
                || comboBox2.SelectedItem == null)
            {
                HinweisLabel.ForeColor = Color.Red; 
                HinweisLabel.Text = "\n Bitte gib erst alle Werte ein! ";
                HinweisLabel.ForeColor = Color.Black; 
     
                return;
            }
            for (int j = 0; j < textBox2.Text.Length; j++)
            {
                if ((textBox2.Text[j] != '0') &&
                    (textBox2.Text[j] != '1') &&
                    (textBox2.Text[j] != '2') &&
                    (textBox2.Text[j] != '3') &&
                    (textBox2.Text[j] != '4') &&
                    (textBox2.Text[j] != '5') &&
                    (textBox2.Text[j] != '6') &&
                    (textBox2.Text[j] != '7') &&
                    (textBox2.Text[j] != '8') &&
                    (textBox2.Text[j] != '9') &&
                    (textBox2.Text[j] != '-') &&
                    (textBox2.Text[j] != '.') &&
                    (textBox2.Text[j] != ','))
                {
                    HinweisLabel.ForeColor = Color.Red; 
                    HinweisLabel.Text = "\n Nur numerische Werte erlaubt!";
                    HinweisLabel.ForeColor = Color.Black; 
                    return;
                }
            }
            double geld = Convert.ToDouble(textBox2.Text);
            if (comboBox2.SelectedItem.ToString() == "Einnahmen")
            {
            }
            else { geld = -geld; }
            if (table.Rows.Count < 1)
            {
                table.Rows.Add(dateTimePicker1.Value, comboBox2.SelectedItem.ToString(), geld, comboBox1.SelectedItem.ToString(), textBox1.Text, geld);
            }
            else
            {
                table.Rows.Add(dateTimePicker1.Value, comboBox2.SelectedItem.ToString(), geld, comboBox1.SelectedItem.ToString(), textBox1.Text, Convert.ToDouble(table.Rows[table.Rows.Count - 1][5]) + geld);
            }
            dataGridView1.DataSource = table;
            setupGrid();
           
            toolStripStatusLabel1.Text = "Daten temporär in Grid übertragen...";
            button2.Enabled = true;
            Speichern.Enabled = true;
            HinweisLabel.Text = "Wenn dir deine Änderung zusagt, kannst du sie nun \n fest in die "
                                   + "DatenBank schreiben. \n \n"
                                   + "Oder verwirf alle nicht gespeicherten Änderungen, \n"
                                    +"mit einem Klick auf 'Verwerfen'.";
            
        }
        
        //delete Cmd
        private void button3_Click(object sender, EventArgs e)
        {
            for (int row = dataGridView1.RowCount-1; row > -1; row--  )
            {
                DataGridViewCheckBoxCell ChkBoxCell = dataGridView1.Rows[row].Cells[0] as DataGridViewCheckBoxCell;
           
                if (ChkBoxCell.Value != null)
                {
                    if ((bool)ChkBoxCell.Value == true) { table.Rows[row].Delete(); }
                }
            }
            button2.Enabled = true;
            Speichern.Enabled = true;
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = table;
            setupGrid();
            setupMoney();
            toolStripStatusLabel1.Text = "Löschen erfolgreich...";
            HinweisLabel.Text = "\n Bitte klicke auf Speichern, um die \n Änderungen wirklich zu übernehemen!";
        }

        //////////////////////////////////////////////////////////////////////////
        /////////////////////////////TIMS DANGER ZONE/////////////////////////////
        //////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Fills the given table with random shit and updates itself into in the DataGridView.
        /// </summary>
        /// <param name="tab">The table to be filled.</param>
        /// <param name="numEntries">Defines how many Entries should be generated.</param>
        /// <param name="future">Generate entries into the future (true = default) (false = TODO)</param>
        private void fillTable(DataTable tab, int numEntries, bool future = true)
        {
            System.Random random = new System.Random();
            DateTime currentDate;

            // resulting parameters
            string typ;
            double betrag;
            string kategorie;
            string beschreibung;
            double current;

            // string arrays as possibility arrays for the random entry generator
            string[] kategorie_list = new string[] {
                  "Notfall", "Kontoführungsgebühren", "Massage", "Nachzahlung", "Telefonrechnung"
                , "Geschäftlich", "Haustier", "Essen", "Überziehungszinsen", "Abgeltungssteuer"
                , "Arbeit", "Handwerker", "Reperatur", "Einkauf", "Lebensmittel", "Urlaub", "Raub"
                , "Tribut", "Wegzoll", "Investition", "Überweisung", "Prostitution", "Leiharbeit"
                , "Schwarzarbeit", "Lifestyle", "Event", "GEZ", "Barzahlung"
            };

            string[] beschreibung_list = new string[] {
                  "Ein Angebot, dass man nicht ablehnen kann."
                , "Die Axt im Haus, erspart den Zimmermann."
                , "Besser den Spatz in der Hand, als die Taube auf dem Dach."
                , "War schön bei deiner Mutter!"
                , "Übel, Übel, sprach der Dübel... und verschwand in der Wand, auf dass ihn niemand wiederfand."
                , "Keine Beschreibung ist auch eine Beschreibung."
                , "Das musste mal wieder sein..."
                , "Ich habe es immernoch drauf!"
                , "Es ist ein Geben und Nehmen."
                , "Bei dieser Beschreibung handelt es sich um ein Easteregg."
                , "Eine wie keine."
                , "Man gönnt sich ja sonst nichts."
                , "Alles in Lot auf'm Boot."
                , "Alles in Budder auf'm Kudder."
                , "Da habe ich mal ordentlich den Swag aufgedreht."
                , "Fuffies im Club."
                , "Das macht den Kohl nun auch nicht mehr Fett."
                , "Die Axt im Haus erspart den Zimmermann."
                , "Ganz wat feines!"
            };

            // getting the last item in the last row of the table ("aktuelles guthaben")
            current = tab.Rows.Count >= 1 ? Convert.ToDouble(tab.Rows[table.Rows.Count - 1][tab.Columns.Count - 1]) : 0;
            // getting the first item in the last row of the table ("aktuelles datum")
            currentDate = tab.Rows.Count >= 1 ? Convert.ToDateTime(tab.Rows[table.Rows.Count - 1][0]) : System.DateTime.Now;
            
            // main loop for each new entry
            for (int i = 0; i < numEntries; i++)
            {
                // add a random number of days from the current date (to generate transactions in the future)
                currentDate = currentDate.AddDays(random.Next(4));

                // generate a random sum for later use
                betrag = random.Next(1, 2500);

                // get a random "kategorie" and "beschreibung" text
                kategorie = kategorie_list[random.Next(kategorie_list.Length)];
                beschreibung = beschreibung_list[random.Next(beschreibung_list.Length)];

                // decide whether the "betrag" should be a win or loss. if its a loss, invert "betrag".
                if (random.Next(0, 100) <= 50) { typ = "Einnahmen"; }
                else { typ = "Ausgaben"; betrag = -betrag; }

                // calculate, or better, update the "aktuelles guthaben"
                current += betrag;

                // add the generated entries to the table
                table.Rows.Add(currentDate, typ, betrag, kategorie, beschreibung, current);
            }

            // update the datagridview with the new generated table content
            dataGridView1.DataSource = table;

            setupGrid();
        }

        /// <summary>
        /// Search a given DataTable with expressions.
        /// </summary>
        /// <param name="tab">The DataTable to search.</param>
        /// <param name="filterExpression">http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx</param>
        /// <param name="sort">One or more column names separated by "," followed by "ASC" (ascending) or "DESC" (descending)</param>
        private void searchTable(DataTable tab, string filterExpression, string sort)
        {
            /////////////////////////////DATATABLE METHOD/////////////////////////////
            //////////////////////////////////////////////////////////////////////////

            var query = tab.Select(filterExpression, sort);
            DataTable foundTable = query.CopyToDataTable<DataRow>(); ///< Create a table from the query.
            dataGridView1.DataSource = foundTable; ///< update the datagridview with the new generated table content

            // Various other possibilities
            ///////////////////////////////////LINQ///////////////////////////////////
            //// POSSIBILITY 1
            //var a = tab.AsEnumerable()
            //    .Where(p => p.Field<int>("Stand") > p.Field<int>("Betrag"))
            //    .Select(p => new
            //    {
            //        Datum = p.Field<DateTime>("Datum"),
            //        Typ = p.Field<string>("Typ"),
            //        Betrag = p.Field<double>("Betrag"),
            //        Kategorie = p.Field<String>("Kategorie"),
            //        Beschreibung = p.Field<String>("Beschreibung"),
            //        Stand = p.Field<double>("Stand")
            //    });
            //// POSSIBILITY 2
            // Query the SalesOrderHeader table for orders placed
            // after August 8, 2001.
            //IEnumerable<DataRow> query =
            //    from order in orders.AsEnumerable()
            //    where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)
            //    select order;
            //DataTable boundTable = query.CopyToDataTable<DataRow>(); ///< Create a table from the query.
            //// POSSIBILITY 2
            //var query = from c in table.AsEnumerable()
            //            where c.Field<string>("Week") = 25
            //            select new { Week = c.Field<string>("Week"), Person = c.Field<string>("Person"), Guess = c.Field<string>("Guess"), Actual = c.Field<string>("Actual") };
            //DataTable boundTable = query.CopyToDataTable<DataRow>(); ///< Create a table from the query.
            ///////////////////////////////LINQ & REGEX///////////////////////////////
            //// POSSIBILITY 3
            //DataTable dtoutput = tab.AsEnumerable().Where(a => Regex.IsMatch(a["MYCOLUMNANME"].ToString(), "s.*t.*t"))
            //                                .CopyToDataTable();
            //////////////////////////////////////////////////////////////////////////
        }

        //////////////////////////////////////////////////////////////////////////
        /////////////////////////////TIMS DANGER ZONE/////////////////////////////
        //////////////////////////////////////////////////////////////////////////

        private void button4_Click(object sender, EventArgs e)
        {
            fillTable(table, 5000);
            toolStripStatusLabel1.Text = "Massendaten erfolgreich eingefügt...";
            Speichern.Enabled = true;
            button2.Enabled = true;
            setupMoney();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBox1.ForeColor = System.Drawing.Color.Black;
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBox2.ForeColor = System.Drawing.Color.Black;
        }

        public void setupGrid()
        {
            tabPage1.Text = "Einnahmen/Ausgaben";
            tabPage2.Text ="Einnahmen";
            tabPage3.Text = "Ausgaben";
            for (int i = 0; i < dataGridView1.RowCount; i++)
            {
                // minor bug fixed: cast the table entry to string
                if ((string)table.Rows[i][1] == "Ausgaben")
                {
                    dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.MistyRose;
                }
                else
                {
                    dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightGreen;
                }
            }
            setupStand();
            dataGridView1.Columns[5].Width = 148;
            dataGridView1.AllowUserToResizeColumns = false;

            setupTables();

            for (int i = 0; i < dataGridView2.RowCount; i++)
            {
                // minor bug fixed: cast the table entry to string
                if ((string)EinnahmenDt.Rows[i][1] == "Ausgaben")
                {
                    dataGridView2.Rows[i].DefaultCellStyle.BackColor = Color.MistyRose;
                }
                else
                {
                    dataGridView2.Rows[i].DefaultCellStyle.BackColor = Color.LightGreen;
                }
            }

            for (int i = 0; i < dataGridView3.RowCount; i++)
            {
                // minor bug fixed: cast the table entry to string
                if ((string)AusgabenDt.Rows[i][1] == "Ausgaben")
                {
                    dataGridView3.Rows[i].DefaultCellStyle.BackColor = Color.MistyRose;
                }
                else
                {
                    dataGridView3.Rows[i].DefaultCellStyle.BackColor = Color.LightGreen;
                }
            }
            dataGridView2.Columns[5].Width = 148;
            dataGridView2.AllowUserToOrderColumns = true;
            dataGridView3.Columns[5].Width = 148;
            dataGridView3.AllowUserToOrderColumns = true;
 

        }

        private void KategorieBtn_Click(object sender, EventArgs e)
        {
            Kategorie Kat = new Kategorie();
            String profile = (string)comboBox3.SelectedItem;
            Kat.CurrentProfile = profile; 
            Kat.Show();
        }

        public void setupTables()
        {

            EinnahmenDt = new DataTable();
            EinnahmenDt.Columns.Add("Datum", typeof(DateTime));
            EinnahmenDt.Columns.Add("Typ", typeof(string));
            EinnahmenDt.Columns.Add("Betrag", typeof(double));
            EinnahmenDt.Columns.Add("Kategorie", typeof(String));
            EinnahmenDt.Columns.Add("Beschreibung", typeof(String));
            EinnahmenDt.Columns.Add("Stand", typeof(double));

            AusgabenDt = new DataTable();
            AusgabenDt.Columns.Add("Datum", typeof(DateTime));
            AusgabenDt.Columns.Add("Typ", typeof(string));
            AusgabenDt.Columns.Add("Betrag", typeof(double));
            AusgabenDt.Columns.Add("Kategorie", typeof(String));
            AusgabenDt.Columns.Add("Beschreibung", typeof(String));
            AusgabenDt.Columns.Add("Stand", typeof(double));

            for (int row = 0; row < dataGridView1.Rows.Count; row++ )
            {

                DataRow currentrow = table.NewRow();
                currentrow[0] = (string)dataGridView1.Rows[row].Cells[1].Value.ToString();
                currentrow[1] = (string)dataGridView1.Rows[row].Cells[2].Value.ToString();
                currentrow[2] = (string)dataGridView1.Rows[row].Cells[3].Value.ToString();
                currentrow[3] = (string)dataGridView1.Rows[row].Cells[4].Value.ToString();
                currentrow[4] = (string)dataGridView1.Rows[row].Cells[5].Value.ToString();
                currentrow[5] = (string)dataGridView1.Rows[row].Cells[6].Value.ToString();

             
                // minor bugfix: safety cast to string
                if ((string)table.Rows[row][1] == "Einnahmen")
                {
                    EinnahmenDt.Rows.Add(currentrow[0], currentrow[1], currentrow[2], currentrow[3], currentrow[4], currentrow[5]);
                }
                else
                {
                    AusgabenDt.Rows.Add(currentrow[0], currentrow[1], currentrow[2], currentrow[3], currentrow[4], currentrow[5]);
                }
            }
            dataGridView2.DataSource = EinnahmenDt;
            dataGridView3.DataSource = AusgabenDt;
        }


        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            setupGrid();
            setupChart();
            refreshCategories();
            if (dateTimePicker2.Value == dateTimePicker3.Value)
            {
                dateTimePicker2.Value = dateTimePicker3.Value.AddDays(-7);
            }
        }


        public void setupChart()
        {
            if (dataGridView1.Rows.Count > 0 && dataGridView1 != null)
            {
                //Datumsabhängige dt
                DataTable DateTable = new DataTable();
                //Spaltenköpfe einfügen
                DateTable.Columns.Add("stand", typeof(double));
                DateTable.Columns.Add("date", typeof(DateTime));
                //Datumsabhängigen Inhalt übertragen
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    double stand =Convert.ToDouble(dataGridView1.Rows[i].Cells[6].Value);
                    
                    DateTable.Rows.Add(stand, Convert.ToDateTime(dataGridView1.Rows[i].Cells[1].Value) );
                }
                
           
                chart1.DataSource = DateTable ;
                
                chart1.Series[0].XValueMember = "date";
                chart1.Series[0].YValueMembers = "stand";
                chart1.DataBind();
               
               
               
                


          
            }
        }

        private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
        {
        //deactivatet   --
            filterGrid();
            InitForm();
            setupMoney();
        }

        private void dateTimePicker3_ValueChanged(object sender, EventArgs e)
        {
            //deactivatet  --
            filterGrid();
            InitForm();
            setupMoney();
        }

        public void filterGrid()
        {

            if (table.Rows.Count > 0) {
                dataGridView1.DataSource = table.Copy();
                setupGrid();
            for (int row = table.Rows.Count-1; row > -1; row--)
             
            {
               
            
                DateTime dt = Convert.ToDateTime(table.Rows[row][0]);
                if ((dt > dateTimePicker3.Value) || (dt < dateTimePicker2.Value))
                {

                    dataGridView1.Rows.RemoveAt(row);
                   
                }
            }
            }
           
        }

        private void button5_Click(object sender, EventArgs e)
        {
            Profile profil = new Profile();
            profil.Show();
        }

        private void comboBox3_Dropdown(object sender, EventArgs e)
        {
            if (System.IO.File.Exists("./ProfilData.xml"))
            {
                IOHandler reader = new IOHandler();
                DataTable dt = reader.loadDataTable("", "");
                comboBox3.Items.Clear();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    comboBox3.Items.Add((string)dt.Rows[i][0]);
                }
            }
        }

        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (System.IO.File.Exists("./" + comboBox3.SelectedItem + "/GridData.xml"))
            {
                IOHandler reader = new IOHandler();
                DataTable dt = reader.loadDataTable((string)comboBox3.SelectedItem, "GridData");
                table.Rows.Clear();
                if (dt != null)
                {

                    table = dt;
                }
                dataGridView1.DataSource = null;
                dataGridView1.Rows.Clear();
                dataGridView1.DataSource = table;
                setupGrid();
                InitForm();
            }
                 else{
                     dataGridView1.DataSource = null;
                     dataGridView1.Rows.Clear();
                     table.Rows.Clear();
                     dataGridView1.DataSource = table;
                setupGrid();
    }
                dateTimePicker2.Value = dateTimePicker3.Value.AddDays(-90);
                filterGrid();
                complete_money.Text = "0€";
                setupMoney();
                HinweisLabel.Text = "Auf der Linken Seite kannst \n du nun deine Daten eingeben. \n \n"
                                    +" Mit einem Klick auf 'Übertragen' \n kommen diese dann in "
                                    +"die Tabelle.";
            
        }
   


        private void button2_Click(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = "Verwerfen erfolgreich...";
            setupMoney();
        }

        public void InitProfiles()
        {

            IOHandler reader = new IOHandler();
            DataTable profildt = new DataTable();
           if (File.Exists("./ProfilData.xml")){
            profildt = reader.loadDataTable();
            if (profildt.Rows.Count > 0)
            {
                comboBox3.DataSource = null;
                comboBox3.Items.Clear();
                for (int i = 0; i < profildt.Rows.Count; i++)
                {
                    comboBox3.Items.Add((string)profildt.Rows[i][0]);
                }
            }
            else
            {
                comboBox3.Text = "Erstelle dir ein Profil";
            }
           }
           else{
               comboBox3.Text = "Erstelle dir ein Profil";
           }
        }

        public void refreshCategories()
       {
            IOHandler reader = new IOHandler();
            Kategorietable = reader.loadDataTable((string)comboBox3.SelectedItem, "Kategorie");
            if (Kategorietable != null && Kategorietable.Rows.Count > 0)
            {
                comboBox1.DataSource = null;
                comboBox1.Items.Clear();
                for (int i = 0; i < Kategorietable.Rows.Count; i++)
                {
                    comboBox1.Items.Add(Kategorietable.Rows[i][0]);
                }
            }
            else
            {
                comboBox1.DataSource = null;
                comboBox1.Text = "Bitte auswählen";
                comboBox1.Items.Clear();
            }

        }

        public void combobox1_dropdown(object sender, EventArgs e)
        {
            refreshCategories();
        }

        public void InitForm()
        {
            if (comboBox3.SelectedItem == null)
            {
                groupBox1.Enabled = false;
                button1.Enabled = false;
                button2.Enabled = false;
                button3.Enabled = false;
                button4.Enabled = false;
                button6.Enabled = false;
                Speichern.Enabled = false;
                dateTimePicker2.Enabled = false;
                dateTimePicker3.Enabled = false;
                groupBox3.Enabled = false;
                tabControl1.Enabled = false;
            }
            else
            {
                groupBox1.Enabled = true;
                button1.Enabled = true;
                button2.Enabled = false;
                button3.Enabled = true;
                button4.Enabled = true;
                button6.Enabled = true;
                Speichern.Enabled = false;
                dateTimePicker2.Enabled = true;
                dateTimePicker3.Enabled = true;
                groupBox3.Enabled = true;
                tabControl1.Enabled = true;
            }
     
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = null;
            InitProfiles();

        }

        private void button6_Click(object sender, EventArgs e)
        {
            Dauerauftrag da = new Dauerauftrag();
            String profile = (string)comboBox3.SelectedItem;
            da.CurrentProfile = profile;
            da.Show();
        }

        private void setupMoney()
        {
            double MoneyoverTime = 0.0;
            for (int i =0 ; i < dataGridView1.Rows.Count; i++)
            {
                MoneyoverTime += Convert.ToDouble((string)dataGridView1.Rows[i].Cells[3].Value.ToString());
            }

            cureent_money.Text = Convert.ToString(MoneyoverTime)+"€";

            double MoneyComplete = 0.0;
            for (int i = 0; i < table.Rows.Count; i++)
            {
                MoneyComplete += Convert.ToDouble(table.Rows[i][2]);
            }

            complete_money.Text = Convert.ToString(MoneyComplete) + "€";
        }
       
        private void setupStand()
        {
            if (dataGridView1 != null && dataGridView1.RowCount > 0)
            {
                double currentvalue = Convert.ToDouble(dataGridView1.Rows[0].Cells[3].Value.ToString());
                dataGridView1.Rows[0].Cells[6].Value = currentvalue;
                for (int i = 1; i < dataGridView1.RowCount; i++)
                {
                    currentvalue += Convert.ToDouble(dataGridView1.Rows[i].Cells[3].Value.ToString());
                    dataGridView1.Rows[i].Cells[6].Value = currentvalue;
                }
            }
        }

       protected void dataGridView1_ColumnsSortModeChanged(object sender, EventArgs e)
        {
             
            setupGrid();
            setupStand();
        }

       private void InitToolTips()
       {
           ToolTip toolTip = new ToolTip();
           toolTip.SetToolTip(Speichern, "Änderungen in Datenbank übertragen");
           toolTip.SetToolTip(button1, "In Tabelle übertragen.(Nicht fest Speichern!)");
           toolTip.SetToolTip(button3, "Markierte Einträge löschen");
           toolTip.SetToolTip(button6, "Dauerauftrag anlegen");
           toolTip.SetToolTip(KategorieBtn, "Neue Kategorie hinzufügen");
           toolTip.SetToolTip(button5, "Neues Profil anlegen");
           toolTip.SetToolTip(button2, "Noch nicht gespeicherte Änderungen verwerfen");
           toolTip.SetToolTip(button4, "Testdaten hinzufügen");

       }
         
    }

    
}